/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package view.inventory;

import java.awt.Component;
import java.awt.KeyboardFocusManager;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.List;
import javax.swing.*;
import main.ServicesList;
import model.inventory.*;
import org.apache.log4j.Logger;
import utility.Constants;
import utility.NameValueList;
import utility.com.TextComponentUtils;
import utility.typeSafe.EnumUtils;
import utility.typeSafe.ItemPerfoma;
import view.lookup.LookupDeptFrm;
import view.lookup.LookupSimpleFrm;

/**
 *
 * @author jay
 */
public class HadiahFrm extends javax.swing.JDialog {

    private Hadiah item;
    private Object oldValue, newValue;
    //private List<NameValueList> performList = EnumUtils.enumToNameValueList(ItemPerfoma.class);
    private static Logger log = Logger.getLogger(HadiahFrm.class);
    
    public HadiahFrm() {
        super(ServicesList.MAIN_FRAME, true);
        initComponents();
        initComponentsRules();
    }

    public int execute(int id) {
        setLocationRelativeTo(null);
        initForm();
        if (id!=0) { loadData(id); }

        setVisible(true);
        if (item!=null) {
        return item.getId();}
        else { return 0; }
    }

    public void initButtonState(boolean status){
        btnSave.setEnabled(status);
    }
    
    public void initForm(){
        item = new Hadiah();
        
        txtNama.setText("");
        txtKode.setText("");      
        txtSatuan.setText("");        
    }
    
    public void loadData(int id){
        item = ServicesList.getHadiahService().getHadiah(id);
        if (item != null) {            
            txtKode.setText(item.getPlu());
            txtNama.setText(item.getNama());
            
            
            if (item.getMstUnit() != null) { txtSatuan.setText(item.getMstUnit().getNama()); }
            
        }
    }
    
    public void saveData(){
        
        
        item.setNama(txtNama.getText());
        
        item.setPlu(txtKode.getText());
          
//        item.setUnit(unit);
//        item.setDept(dept);
        boolean saved = false;
        try{
            saved = ServicesList.getHadiahService().save(item);
            
        } catch(Exception ex){
            log.error(ex);
            JOptionPane.showMessageDialog(this, "Data gagal disimpan."
            ,"Error",JOptionPane.ERROR_MESSAGE);
        }
        
        initButtonState(!saved);
    }
    
    public void validasi(){
        boolean valid;
        
        valid = txtNama.getText().equals("") ? false:true;
        if (!valid) {
            JOptionPane.showMessageDialog(this, "Nama belum diisi.!"
            ,"Warinig",JOptionPane.WARNING_MESSAGE);}
        
        if (valid) { saveData(); }
    }
    
    private void lookupMaster(int purpose, String param) {
        Object object;
        if (purpose==Constants.LOOKUP_DEPT) {
            object = new LookupDeptFrm().execute();
        } else {
            object = new LookupSimpleFrm().execute(purpose, param);
        }
                
        if (object != null) {
            setMaster(purpose, object);
        }
    }
    
    private void setMaster(int purpose, Object object) {
         if (object != null) {
            switch (purpose) {
                
                    
                case Constants.LOOKUP_UNIT:
                    item.setMstUnit((Unit) object);
                    txtSatuan.setText(item.getMstUnit().getNama());
                    
                    break;
                default: break;    
            }
        }
    }
    
    private void getMaster(int purpose, String kode) {
        switch (purpose) {
           
               
           case Constants.LOOKUP_UNIT:
               item.setMstUnit(ServicesList.getUnitService().getUnit(kode));
               if (item.getMstUnit() != null) {
                   setMaster(purpose, item.getMstUnit());
               }else { lookupMaster(purpose, txtSatuan.getText()); }
               break;
               
           default: break;    
        }
    }
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        txtKode = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        txtNama = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        txtSatuan = new javax.swing.JTextField();
        jLabel9 = new javax.swing.JLabel();
        jToolBar1 = new javax.swing.JToolBar();
        btnAdd = new javax.swing.JButton();
        btnSave = new javax.swing.JButton();
        btnClose = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        txtKode.setText("jTextField1");
        txtKode.setName("txtKode"); // NOI18N

        jLabel1.setText("PLU :");

        txtNama.setText("jTextField1");
        txtNama.setName("txtNama"); // NOI18N

        jLabel6.setText("Nama :");

        txtSatuan.setText("jTextField1");
        txtSatuan.setName("txtSatuan"); // NOI18N

        jLabel9.setText("Satuan :");

        jToolBar1.setFloatable(false);
        jToolBar1.setRollover(true);
        jToolBar1.setSize(this.getWidth(), 50);

        btnAdd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/edit_add.png"))); // NOI18N
        btnAdd.setText("Tambah");
        btnAdd.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnAdd.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddActionPerformed(evt);
            }
        });

        btnSave.setIcon(new javax.swing.ImageIcon(getClass().getResource("/filesave.png"))); // NOI18N
        btnSave.setText("Simpan");
        btnSave.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnSave.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveActionPerformed(evt);
            }
        });

        btnClose.setIcon(new javax.swing.ImageIcon(getClass().getResource("/cancel.png"))); // NOI18N
        btnClose.setText("Close");
        btnClose.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnClose.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCloseActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(21, 21, 21)
                        .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 264, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(31, 31, 31)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel6)
                            .addComponent(jLabel9))
                        .addGap(10, 10, 10)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtNama, javax.swing.GroupLayout.PREFERRED_SIZE, 207, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtKode, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtSatuan, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(57, 57, 57)
                        .addComponent(btnAdd)
                        .addComponent(btnSave)
                        .addComponent(btnClose)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtKode, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtNama, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtSatuan, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel9))
                .addGap(71, 71, 71)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnAdd)
                    .addComponent(btnSave)
                    .addComponent(btnClose))
                .addGap(166, 166, 166)
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
        initForm();
        txtKode.requestFocus();
    }//GEN-LAST:event_btnAddActionPerformed

    private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
        validasi();
    }//GEN-LAST:event_btnSaveActionPerformed

    private void btnCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCloseActionPerformed
        dispose();
    }//GEN-LAST:event_btnCloseActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnClose;
    private javax.swing.JButton btnSave;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JTextField txtKode;
    private javax.swing.JTextField txtNama;
    private javax.swing.JTextField txtSatuan;
    // End of variables declaration//GEN-END:variables
    
    @Override
    public void setVisible(boolean value) {
        super.setVisible(value);
        txtKode.requestFocusInWindow();
    }
    
    public void moveNext() {
        KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
        manager.focusNextComponent();
    }
    
    class ActionKeyListener implements KeyListener {
        @Override public void keyTyped(KeyEvent e) {} 
        @Override public void keyReleased(KeyEvent e) {}
        
        @Override public void keyPressed(KeyEvent e) {
            switch (e.getKeyCode()) { 
                case KeyEvent.VK_F2: 
                    switch(e.getComponent().getName()) {                        
                        case "txtSatuan": lookupMaster(Constants.LOOKUP_UNIT, txtSatuan.getText()); break;
                    };
                break;  
                
                case KeyEvent.VK_ENTER: 
                    switch(e.getComponent().getName()) {
                       
                            
                        case "txtSatuan": 
                            newValue = txtSatuan.getText();
                            if (!newValue.equals(oldValue)) { getMaster(Constants.LOOKUP_UNIT, txtSatuan.getText()); }
                            else {moveNext();}
                            break;
                            
                       default: moveNext(); break;
                    };
                    
                break;      
            }
        }
    }
    
    class ActionFocusGained implements FocusListener {
        @Override public void focusGained(FocusEvent e) { 
            Component componen = (Component) e.getSource(); 
            if (componen instanceof JTextField) { oldValue = ((JTextField) componen).getText();
            }else if (componen instanceof JComboBox) { oldValue = ((JComboBox) componen).getSelectedIndex();
            }else if (componen instanceof JCheckBox) { oldValue = ((JCheckBox) componen).isSelected();
            }else if (componen instanceof JTextArea) { oldValue = ((JTextArea) componen).getText(); }
        }
        
        @Override public void focusLost(FocusEvent e) {
            Component componen = (Component) e.getSource(); 
            if (componen instanceof JTextField) { newValue = ((JTextField) componen).getText();
            }else if (componen instanceof JComboBox) { newValue = ((JComboBox) componen).getSelectedIndex();
            }else if (componen instanceof JCheckBox) { newValue = ((JCheckBox) componen).isSelected();
            }else if (componen instanceof JTextArea) { oldValue = ((JTextArea) componen).getText(); }
            if (!newValue.equals(oldValue)) { initButtonState(true); }
        }
    }
    
    private void initComponentsRules() {
        btnClose.registerKeyboardAction(btnAdd.getActionForKeyStroke(
            KeyStroke.getKeyStroke(KeyEvent .VK_SPACE, 0, false)), KeyStroke.getKeyStroke(KeyEvent .VK_ENTER, 0, false), JComponent.WHEN_FOCUSED);
 
        btnClose.registerKeyboardAction(btnAdd.getActionForKeyStroke(
            KeyStroke.getKeyStroke(KeyEvent .VK_SPACE, 0, true)), KeyStroke.getKeyStroke(KeyEvent .VK_ENTER, 0, true), JComponent.WHEN_FOCUSED);
        
        btnAdd.registerKeyboardAction(btnAdd.getActionForKeyStroke(
            KeyStroke.getKeyStroke(KeyEvent .VK_SPACE, 0, false)), KeyStroke.getKeyStroke(KeyEvent .VK_ENTER, 0, false), JComponent.WHEN_FOCUSED);

        btnAdd.registerKeyboardAction(btnAdd.getActionForKeyStroke(
            KeyStroke.getKeyStroke(KeyEvent .VK_SPACE, 0, true)), KeyStroke.getKeyStroke(KeyEvent .VK_ENTER, 0, true), JComponent.WHEN_FOCUSED);

        btnSave.registerKeyboardAction(btnSave.getActionForKeyStroke(
            KeyStroke.getKeyStroke(KeyEvent .VK_SPACE, 0, false)), KeyStroke.getKeyStroke(KeyEvent .VK_ENTER, 0, false), JComponent.WHEN_FOCUSED);
 
        btnSave.registerKeyboardAction(btnSave.getActionForKeyStroke(
            KeyStroke.getKeyStroke(KeyEvent .VK_SPACE, 0, true)), KeyStroke.getKeyStroke(KeyEvent .VK_ENTER, 0, true), JComponent.WHEN_FOCUSED);
        
        
        
        
        txtKode.addKeyListener(new ActionKeyListener());
        txtKode.addFocusListener(new ActionFocusGained());        
        txtNama.addKeyListener(new ActionKeyListener());
        txtNama.addFocusListener(new ActionFocusGained());
        txtSatuan.addFocusListener(new ActionFocusGained());
        txtSatuan.addKeyListener(new ActionKeyListener());
    }      
    

}
